package com.yf.openapi.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yf.ability.shiro.dto.SysUserLoginDTO;
import com.yf.base.api.api.ApiError;
import com.yf.base.api.exception.ServiceException;
import com.yf.base.utils.passwd.PassHandler;
import com.yf.base.utils.passwd.PassInfo;
import com.yf.openapi.modules.user.service.OpenUserService;
import com.yf.system.modules.depart.service.SysDepartService;
import com.yf.system.modules.user.entity.SysUser;
import com.yf.system.modules.user.enums.SysRoleId;
import com.yf.system.modules.user.enums.UserState;
import com.yf.system.modules.user.service.SysUserRoleService;
import com.yf.system.modules.user.service.SysUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OpenUserServiceImpl implements OpenUserService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDepartService sysDepartService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public SysUserLoginDTO syncLogin(String userId, String userName, String realName, String roles, String departs) {

        SysUser user;

        // 有ID
        if (!StringUtils.isBlank(userId)) {
            user = sysUserService.getById(userId);
        } else {
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SysUser::getUserName, userName);
            user = sysUserService.getOne(wrapper, false);
        }

        // 检查用户并登录
        if (user != null) {
            return this.checkAndLogin(user);
        } else {
            String deptCode = sysDepartService.syncDepart(departs);
            return this.saveAndLogin(userId, userName, deptCode, realName, roles);
        }
    }

    /**
     * 用户登录校验
     *
     * @param user
     */
    private SysUserLoginDTO checkAndLogin(SysUser user) {

        // 被禁用
        if (UserState.DISABLED.equals(user.getState())) {
            throw new ServiceException(ApiError.ERROR_90010005);
        }

        // 待审核
        if (UserState.AUDIT.equals(user.getState())) {
            throw new ServiceException(ApiError.ERROR_90010006);
        }

        return sysUserService.setToken(user);
    }

    /**
     * 保存用户并登录
     * @param userId
     * @param userName
     * @param deptCode
     * @param realName
     * @param role
     * @return
     */
    private SysUserLoginDTO saveAndLogin(String userId, String userName, String deptCode, String realName, String role) {

        // 保存用户
        SysUser user = new SysUser();

        // 指定用户ID的
        if (!StringUtils.isBlank(userId)) {
            user.setId(userId);
        } else {
            user.setId(IdWorker.getIdStr());
        }

        user.setState(UserState.NORMAL);
        user.setUserName(userName);
        user.setRealName(realName);
        user.setDeptCode(deptCode);
        PassInfo passInfo = PassHandler.buildPassword(RandomStringUtils.randomAlphanumeric(32));
        user.setPassword(passInfo.getPassword());
        user.setSalt(passInfo.getSalt());

        // 保存角色
        List<String> roleList = new ArrayList<>();
        if (!StringUtils.isBlank(role)) {
            roleList.add(role);
        } else {
            // 默认学员
            roleList.add(SysRoleId.STUDENT);
        }

        // 保存角色
        sysUserRoleService.saveRoles(user.getId(), roleList, false);

        // 保存用户
        sysUserService.save(user);

        return sysUserService.setToken(user);
    }
}
